package com.xh.shuati.service.impl;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.benmanes.caffeine.cache.Cache;
import com.jd.platform.hotkey.client.callback.JdHotKeyStore;
import com.xh.shuati.common.ErrorCode;
import com.xh.shuati.constant.CommonConstant;
import com.xh.shuati.exception.BusinessException;
import com.xh.shuati.exception.ThrowUtils;
import com.xh.shuati.manager.AiManager;
import com.xh.shuati.mapper.QuestionMapper;
import com.xh.shuati.model.dto.question.QuestionEsDTO;
import com.xh.shuati.model.dto.question.QuestionQueryRequest;
import com.xh.shuati.model.entity.Question;
import com.xh.shuati.model.entity.QuestionBankQuestion;
import com.xh.shuati.model.entity.User;
import com.xh.shuati.model.enums.UserRoleEnum;
import com.xh.shuati.model.vo.QuestionVO;
import com.xh.shuati.model.vo.UserVO;
import com.xh.shuati.service.QuestionBankQuestionService;
import com.xh.shuati.service.QuestionService;
import com.xh.shuati.service.UserService;
import com.xh.shuati.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

import static com.xh.shuati.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 题目服务实现
 *
 * @author <a href="https://github.com/canon0521">xh</a>
 */
@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    /**
     * 通用前缀
     */
    private final String QUESTION_PREFIX = "question:";

    /**
     * 本地Caffeine缓存
     */
    @Resource(name ="questionCache")
    private Cache<String, Object> questionCache;

    @Resource(name ="userCache")
    private Cache<String, Object> userCache;

    @Resource
    private final UserService userService;

    @Resource
    private final QuestionBankQuestionService questionBankQuestionService;

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Resource
    private AiManager  aiManager;

    public QuestionServiceImpl(UserService userService,@Lazy QuestionBankQuestionService questionBankQuestionService) {
        this.userService = userService;
        this.questionBankQuestionService = questionBankQuestionService;
    }


    /**
     * 根据ID删除题目
     * @param quesiton
     * @return
     */
    //Todo 优化事务粒度
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteQuestionById(Question quesiton) {
        //1.参数校验
        Long questionId = quesiton.getId();
        String cacheQuestionId = QUESTION_PREFIX + questionId;
        ThrowUtils.throwIf(questionId == null, ErrorCode.PARAMS_ERROR
                ,"增加题目错误,请重试");
        //2.删除数据库
        boolean saved = updateById(quesiton);
        //3.更新HotKey
        if (JdHotKeyStore.isHotKey(cacheQuestionId)) {
            //删除HotKey
            JdHotKeyStore.remove(cacheQuestionId);
            //Todo 将值设置为null,避免热Key高并发造成数据库崩溃
            questionCache.put(questionId.toString(), null);
        }
        //4.更新Caffeine
        questionCache.invalidate(questionId);
        // 5.返回结果
        return saved;
    }

    /**
     * 根据ID获取问题(优先缓存)
     * @param id
     * @return
     */
    @Override
    public Question getQuestionById(Long id) {
        //1.先从Caffeine从获取
        Object cacheQuestion = questionCache.getIfPresent(Long.toString(id));
        if(cacheQuestion!= null){
            return (Question) cacheQuestion;
        }
        //2.从HotKey中获取
        String hotKeyQuestion = QUESTION_PREFIX + id;
        if(JdHotKeyStore.isHotKey(hotKeyQuestion)){
            Question question = (Question) JdHotKeyStore.get(hotKeyQuestion);
            JdHotKeyStore.smartSet(hotKeyQuestion, question);
            return question;
        }
        //3.如果不存在,从数据库查询
        Question question = getById(id);
        ThrowUtils.throwIf(question == null, ErrorCode.PARAMS_ERROR, "问题不存在");
        //4.存入缓存
        questionCache.put(Long.toString(id), question);
        return question;
    }

    /**
     * 校验数据
     *
     * @param question
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validQuestion(Question question, boolean add) {
        ThrowUtils.throwIf(question == null, ErrorCode.PARAMS_ERROR);
        // todo 从对象中取值
        String title = question.getTitle();
        String content = question.getContent();

        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(title), ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        // todo 补充校验规则
        if (StringUtils.isNotBlank(title)) {
            ThrowUtils.throwIf(title.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(content)) {
            ThrowUtils.throwIf(content.isEmpty(), ErrorCode.PARAMS_ERROR, "内容不能为空");
        }
    }

    /**
     * 获取查询条件
     *
     * @param questionQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Question> getQueryWrapper(QuestionQueryRequest questionQueryRequest) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        if (questionQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = questionQueryRequest.getId();
        Long notId = questionQueryRequest.getNotId();
        String title = questionQueryRequest.getTitle();
        String content = questionQueryRequest.getContent();
        String searchText = questionQueryRequest.getSearchText();
        String sortField = questionQueryRequest.getSortField();
        String sortOrder = questionQueryRequest.getSortOrder();
        List<String> tagList = questionQueryRequest.getTags();
        Long userId = questionQueryRequest.getUserId();
        String answer = questionQueryRequest.getAnswer();
        // todo 补充需要的查询条件
        // 从多字段中搜索
        if (StringUtils.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.like(StringUtils.isNotBlank(answer), "answer", answer);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tagList)) {
            for (String tag : tagList) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取题目封装
     *
     * @param question
     * @return
     */
    @Override
    public QuestionVO getQuestionVO(Question question) {
        // 对象转封装类
        QuestionVO questionVO = QuestionVO.objToVo(question);

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = question.getUserId();
        if (userId != null && userId > 0) {
            UserVO cacheUserVO = (UserVO) userCache.getIfPresent(Long.toString(userId));
            if(cacheUserVO!= null){
                questionVO.setUser(cacheUserVO);

            }
            else{
                //2.如果不存在,从数据库查询
                try{
                    User user = userService.getById(userId);
                    UserVO userVO = userService.getUserVO(user);
                    //4.存入缓存
                    userCache.put(Long.toString(userId), userVO);
                    questionVO.setUser(userVO);
                } catch (Exception e) {
                    ThrowUtils.throwIf(true,ErrorCode.SYSTEM_ERROR);
                }
            }
        }
        else{
            questionVO.setUser(null);
        }
        return questionVO;
    }

    /**
     * 分页获取题目封装
     *
     * @param questionPage
     * @param request
     * @return
     */
    @Override
    public Page<QuestionVO> getQuestionVOPage(Page<Question> questionPage, HttpServletRequest request) {
        List<Question> questionList = questionPage.getRecords();
        Page<QuestionVO> questionVOPage = new Page<>(questionPage.getCurrent(), questionPage.getSize(), questionPage.getTotal());
        if (CollUtil.isEmpty(questionList)) {
            return questionVOPage;
        }
        // 对象列表 => 封装对象列表
        List<QuestionVO> questionVOList = questionList.stream().map(question -> {
            return QuestionVO.objToVo(question);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionList.stream().map(Question::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 已登录，获取用户点赞、收藏状态
//        Map<Long, Boolean> questionIdHasThumbMap = new HashMap<>();
//        Map<Long, Boolean> questionIdHasFavourMap = new HashMap<>();
//        User loginUser = userService.getLoginUserPermitNull(request);
//        if (loginUser != null) {
//            Set<Long> questionIdSet = questionList.stream().map(Question::getId).collect(Collectors.toSet());
//            loginUser = userService.getLoginUser(request);
//            // 获取点赞
//            QueryWrapper<QuestionThumb> questionThumbQueryWrapper = new QueryWrapper<>();
//            questionThumbQueryWrapper.in("questionId", questionIdSet);
//            questionThumbQueryWrapper.eq("userId", loginUser.getId());
//            List<QuestionThumb> questionQuestionThumbList = questionThumbMapper.selectList(questionThumbQueryWrapper);
//            questionQuestionThumbList.forEach(questionQuestionThumb -> questionIdHasThumbMap.put(questionQuestionThumb.getQuestionId(), true));
//            // 获取收藏
//            QueryWrapper<QuestionFavour> questionFavourQueryWrapper = new QueryWrapper<>();
//            questionFavourQueryWrapper.in("questionId", questionIdSet);
//            questionFavourQueryWrapper.eq("userId", loginUser.getId());
//            List<QuestionFavour> questionFavourList = questionFavourMapper.selectList(questionFavourQueryWrapper);
//            questionFavourList.forEach(questionFavour -> questionIdHasFavourMap.put(questionFavour.getQuestionId(), true));
//        }
        // 填充信息
        questionVOList.forEach(questionVO -> {
            Long userId = questionVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionVO.setUser(userService.getUserVO(user));
//            questionVO.setHasThumb(questionIdHasThumbMap.getOrDefault(questionVO.getId(), false));
//            questionVO.setHasFavour(questionIdHasFavourMap.getOrDefault(questionVO.getId(), false));
        });
        // endregion

        questionVOPage.setRecords(questionVOList);
        return questionVOPage;
    }

    /**
     * 降级策略从缓存遍历返回
     */
    @Override
    public Page<QuestionVO> getQuestionFromCache(QuestionQueryRequest request){
        //1.获取分页参数
        int page = request.getCurrent();
        int size = request.getPageSize();
        Page<QuestionVO> questionVOPage = new Page<>(page, size);
        //2.获取缓存中的数据
        @SuppressWarnings("unchecked")
        ConcurrentMap<Long, Question> questionCacheMap =
                (ConcurrentMap<Long, Question>) (ConcurrentMap<?, ?>) questionCache.asMap();
        if(CollUtil.isEmpty(questionCacheMap)){
            return new Page<>(1, 10, 0);
        }
        List<QuestionVO> questionVOList = questionCacheMap.values().stream()
                .filter(Objects::nonNull).map(question -> getQuestionVO(question)) // 可选：过滤 null 值
                .collect(Collectors.toList());
        questionVOPage.setRecords(questionVOList);
        return  questionVOPage;
    }


    /**
     * 分页获取题目列表（仅管理员可用）
     *
     * @param questionQueryRequest
     * @return
     */
    public Page<Question> listQuestionByPage(QuestionQueryRequest questionQueryRequest) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        //题目表的查询条件
        QueryWrapper<Question> queryWrapper = this.getQueryWrapper(questionQueryRequest);

        Long questionBankId = questionQueryRequest.getQuestionBankId();
        if (questionBankId != null) {
            //查询题库下的题目
            LambdaQueryWrapper<QuestionBankQuestion> lambdaQueryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class).
                    select(QuestionBankQuestion::getQuestionId).
                    eq(QuestionBankQuestion::getQuestionBankId, questionBankId);
            List<QuestionBankQuestion> questionList = questionBankQuestionService.list(lambdaQueryWrapper);
            if (CollUtil.isNotEmpty(questionList)) {
                Set<Long> questionIdSet = questionList.stream().map(QuestionBankQuestion::getQuestionId).collect(Collectors.toSet());
                queryWrapper.in("id", questionIdSet);
            } else {
                //搜索结果为空,返回空
                return new Page<>();
            }
        }
        // 查询数据库
        Page<Question> questionPage = this.page(new Page<>(current, size),queryWrapper);
        return questionPage;
    }

    @Override
    public Page<Question> searchFromEs(QuestionQueryRequest questionQueryRequest) {
        Long id = questionQueryRequest.getId();
        Long notId = questionQueryRequest.getNotId();
        String searchText = questionQueryRequest.getSearchText();
        String title = questionQueryRequest.getTitle();
        String content = questionQueryRequest.getContent();
        List<String> tagList = questionQueryRequest.getTags();
//        List<String> orTagList = questionQueryRequest.getOrTags();
        Long userId = questionQueryRequest.getUserId();
        // es 起始页为 0
        long current = questionQueryRequest.getCurrent() - 1;
        long pageSize = questionQueryRequest.getPageSize();
        String sortField = questionQueryRequest.getSortField();
        String sortOrder = questionQueryRequest.getSortOrder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 精确查询 过滤
        boolQueryBuilder.filter(QueryBuilders.termQuery("isDelete", 0));
        if (id != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("id", id));
        }
        if (notId != null) {
            boolQueryBuilder.mustNot(QueryBuilders.termQuery("id", notId));
        }
        if (userId != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("userId", userId));
        }
        // 必须包含所有标签
        if (CollUtil.isNotEmpty(tagList)) {
            for (String tag : tagList) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("tags", tag));
            }
        }
//        // 包含任何一个标签即可
//        if (CollUtil.isNotEmpty(orTagList)) {
//            BoolQueryBuilder orTagBoolQueryBuilder = QueryBuilders.boolQuery();
//            for (String tag : orTagList) {
//                orTagBoolQueryBuilder.should(QueryBuilders.termQuery("tags", tag));
//            }
//            orTagBoolQueryBuilder.minimumShouldMatch(1);
//            boolQueryBuilder.filter(orTagBoolQueryBuilder);
//        }
        // 按关键词检索
        if (StringUtils.isNotBlank(searchText)) {
            //should = or : title or description or content = xx
            boolQueryBuilder.should(QueryBuilders.matchQuery("title", searchText));
            boolQueryBuilder.should(QueryBuilders.matchQuery("description", searchText));
            boolQueryBuilder.should(QueryBuilders.matchQuery("content", searchText));
            //任意一个匹配即可
            boolQueryBuilder.minimumShouldMatch(1);
        }
        // 按标题检索
        if (StringUtils.isNotBlank(title)) {
            boolQueryBuilder.should(QueryBuilders.matchQuery("title", title));
            boolQueryBuilder.minimumShouldMatch(1);
        }
        // 按内容检索
        if (StringUtils.isNotBlank(content)) {
            boolQueryBuilder.should(QueryBuilders.matchQuery("content", content));
            boolQueryBuilder.minimumShouldMatch(1);
        }
        // 排序
        SortBuilder<?> sortBuilder = SortBuilders.scoreSort();
        if (StringUtils.isNotBlank(sortField)) {
            sortBuilder = SortBuilders.fieldSort(sortField);
            sortBuilder.order(CommonConstant.SORT_ORDER_ASC.equals(sortOrder) ? SortOrder.ASC : SortOrder.DESC);
        }
        // 分页
        PageRequest pageRequest = PageRequest.of((int) current, (int) pageSize);
        // 构造查询
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder)
                .withPageable(pageRequest).withSorts(sortBuilder).build();
        SearchHits<QuestionEsDTO> searchHits = elasticsearchRestTemplate.search(searchQuery, QuestionEsDTO.class);
        Page<Question> page = new Page<>();
        page.setTotal(searchHits.getTotalHits());
        List<Question> resourceList = new ArrayList<>();
        // 查出结果后，从 db 获取最新动态数据（比如点赞数）
        if (searchHits.hasSearchHits()) {
            List<SearchHit<QuestionEsDTO>> searchHitList = searchHits.getSearchHits();
            List<Long> questionIdList = searchHitList.stream().map(searchHit -> searchHit.getContent().getId())
                    .collect(Collectors.toList());
            List<Question> questionList = baseMapper.selectBatchIds(questionIdList);
            if (questionList != null) {
                Map<Long, List<Question>> idQuestionMap = questionList.stream().collect(Collectors.groupingBy(Question::getId));
                questionIdList.forEach(questionId -> {
                    if (idQuestionMap.containsKey(questionId)) {
                        resourceList.add(idQuestionMap.get(questionId).get(0));
                    } else {
                        // 从 es 清空 db 已物理删除的数据
                        String delete = elasticsearchRestTemplate.delete(String.valueOf(questionId), QuestionEsDTO.class);
                        log.info("delete question {}", delete);
                    }
                });
            }
        }
        page.setRecords(resourceList);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleQuestions(List<Long> questionids) {
        ThrowUtils.throwIf(CollUtil.isEmpty(questionids), ErrorCode.PARAMS_ERROR,"要删除的题目列表不能为空");
        List<String> cacheDeleteList = new ArrayList<>();
        Object userObj = StpUtil.getSession().get(USER_LOGIN_STATE);
        User user = (User) userObj;
        questionids.forEach(questionId -> {
            Question oldQuestion = getById(questionId);
            if (user.getUserRole().equals( UserRoleEnum.ADMIN.getValue()) || oldQuestion.getUserId().equals(user.getId())){
                oldQuestion.setIsDelete(1);
                oldQuestion.setEditTime(new Date());
                oldQuestion.setCloseChangeId(user.getId());
                boolean isremoved = deleteQuestionById(oldQuestion);
                ThrowUtils.throwIf(!isremoved, ErrorCode.OPERATION_ERROR,  "删除题目失败");
                //移除题目和题库的关系
                //批量从缓存中删除
                questionCache.invalidateAll(cacheDeleteList);
                LambdaQueryWrapper<QuestionBankQuestion> lambdaQueryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class).eq(QuestionBankQuestion::getQuestionId, questionId);
                boolean isremove = questionBankQuestionService.remove(lambdaQueryWrapper);
                ThrowUtils.throwIf(!isremove, ErrorCode.OPERATION_ERROR,  "删除题库题目关联失败");
            }else {
                ThrowUtils.throwIf(true,ErrorCode.NOT_VISIT,"删除题目无权限");
            }


        });
    }

    @Override
    public boolean aiGenerateQuestions(String quetionType, Integer number,  User user) {
        if(ObjectUtil.hasEmpty(quetionType,number)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        //1.定义系统Prompt
        String systemPrompt = "你是一位专业的Java程序员面试官，帮我生成 {数量} 道 {方向} 的面试题，要求输出格式如下：\n" +
                "\n" +
                "1. 什么是Java中的反射？\n" +
                "2. Java8中Stream API 有什么用？\n" +
                "3. xxxxx\n" +
                "\n" +
                "不要输出任何其他多余的东西，不要输入开头和结尾，只输出上面的列表\n" +
                "\n" +
                "接下来的提问中会给你题目的 {数量} 和 {方向}";
        //2.拼接用户Prompt
        String userPrompt = String.format("数量：%s,方向：%s", number, quetionType);
        //3.调用AI生成题目
        String answer = aiManager.doChat(systemPrompt, userPrompt);
        //4.对生成的题目进行处理
        List<String> questions = Arrays.stream(answer.split("\n"))
                .filter(StrUtil::isNotBlank)  // 过滤空行
                .map(question ->
                        // 移除行首的序号（如 "1. "、"2. "）
                        question.replaceAll("^\\d+\\.\\s*", "")
                                // 移除单引号（可选）
                                .replaceAll("‘|’", "")
                )
                .collect(Collectors.toList());
        //5.保存到数据库
        boolean isSuccess = this.saveBatch(questions.stream().map(questionTitle -> {
                    Question question = new Question();
                    question.setUserId(user.getId());
                    question.setTitle(questionTitle);
                    question.setTags("[\"待审核\"]");
                    question.setAnswer(aiGenerateAnswers(questionTitle));
                    question.setCloseChangeId(user.getId());
                    return question;
                })
                .collect(Collectors.toList()));

        if (!isSuccess){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目保存失败");
        }

        return true;
    }

    private  String aiGenerateAnswers(String quetionTitile) {
        String systemPrompt = "你是一位专业的Java程序员面试官，我会给你一道面试题，按下面的要求生成详细题解下：\n" +
                "\n" +
                "1. 题解的语句要自然流畅\n" +
                "2. 题解可以先给出总结性答案，再详细解释\n" +
                "3. 使用MarkDown语法进行回答\n" +
                "除此之外，不要输出任何其他多余的东西，不要输入开头和结尾，只输出题解\n" +
                "接下来我会给你题目";
        //2.拼接用户Prompt
        String userPrompt = String.format("题目：%s", quetionTitile);
        //3.调用AI生成题解
        return aiManager.doChat(systemPrompt, userPrompt);
    }

}
